package com.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import jdk.nashorn.internal.runtime.GlobalConstants;

@Controller
@RequestMapping(value = "/login")
public class LoginController {
	private Logger log = Logger.getLogger(LoginController.class);
	@RequestMapping(value = "/logout")
	public String logout(HttpServletResponse response, HttpServletRequest request, HttpSession session)
			throws IOException {
		// 清除session
		Enumeration<String> em = request.getSession().getAttributeNames();
		while (em.hasMoreElements()) {
			request.getSession().removeAttribute(em.nextElement().toString());
		}
		request.getSession().removeAttribute("username");
		request.getSession().invalidate();
		String path = request.getContextPath();
		// 拼接跳转页面路径
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
		return "redirect:" + basePath;
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)//怎么设置为只接受post请求
	public String login(HttpServletResponse response,HttpServletRequest request,@RequestParam("username") String username, @RequestParam("password") String password, ModelMap map) throws IOException {
		log.info("log4j日志，用户登录："+username + "," + password);
		if("张三".equals(username) && "123456".equals(password)) {
			request.getSession().setAttribute("username", username);
			return "home";
		}else {
			map.put("error", "用户名密码错误！");
			return "login";
		}
	}
}